package com.example.zhxy.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.zhxy.mapper.AdminMapper;
import com.example.zhxy.pojo.Admin;
import com.example.zhxy.pojo.LoginForm;
import com.example.zhxy.service.AdminService;
import com.example.zhxy.util.MD5;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.util.StringUtils;

import java.util.List;

@Service
@Transactional
public class AdminServiceImpl extends ServiceImpl<AdminMapper,Admin> implements AdminService{
    @Override
    public Admin login(LoginForm loginForm) {
        QueryWrapper<Admin> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("name",loginForm.getUsername());
        queryWrapper.eq("password", MD5.encrypt(loginForm.getPassword()));
        Admin admin = baseMapper.selectOne(queryWrapper);
        return admin;
    }

    @Override
    public IPage IPage(Page<Admin> page, String adminName) {
        QueryWrapper<Admin> queryWrapper=new QueryWrapper<>();
        if(!StringUtils.isEmpty(adminName)){
            queryWrapper.like("name",adminName);
        }
        queryWrapper.orderByAsc("id");
        return this.page(page,queryWrapper);
    }

    @Override
    public void deleteAdmin(List<Integer> list, Integer userId) {
        for (Integer integer : list) {
            if(integer==userId){
                continue;
            }
            this.removeById(integer);
        }
    }

    @Override
    public boolean updatePwd(String password, String newPassWord, Integer userId) {
        Admin byId = this.getById(userId);
        if(byId.getPassword().equals(MD5.encrypt(password))){
            byId.setPassword(MD5.encrypt(newPassWord));
            this.updateById(byId);
            return true;
        }else {
            return false;
        }
    }


}
